package gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import modelcontroller.Conversation;
import modelcontroller.User;

/**
 *
 * @author Mariam
 */
public class ChatWindow extends JFrame implements ActionListener {

    private ChatGUI parent;
    private JMenuBar menu;
    private JSplitPane splitPane;
    //private JSplitPane splitPane1;
    private ArrayList<ConversationArea> conversations;
    private JList list;
    private JTextArea msgToSend;
    private JButton bSend;
    private JButton bSendFile;
    private JButton bDisconnect;
    private JTabbedPane tabbedPane;

    public ChatWindow(ChatGUI parent) {
        super();
        this.parent = parent;
        initComponents();

    }

    public void initComponents() {

        /*menu = new JMenuBar();
         JMenu filemenu = new JMenu("File");

         JMenu helpmenu = new JMenu("Help");
         menu.add(filemenu);
         menu.add(helpmenu);*/

        JTextArea infos = new JTextArea();
        infos.setEditable(false);
        infos.setForeground(Color.blue);

        list = new JList(parent.model.getConnectedUsers());
        if (parent.model.getConnectedUsers().isEmpty()) {
            infos.setText("Local User : " + parent.model.getLocalUser().toString());
        }

        JScrollPane scrollPanelist = new JScrollPane(list, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

        list.setPrototypeCellValue("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
        conversations = new ArrayList<ConversationArea>();
        conversations.add(ConversationArea.welcomeConversationArea(parent.model.getLocalUser().getUsername()));
        msgToSend = new JTextArea(4, 25);
        bSend = new JButton("Send");
        bSendFile = new JButton("Send File");
        bDisconnect = new JButton("Disconnect");
        //filemenu.add(bDisconnect);


        tabbedPane = new JTabbedPane();
        //for (JTextArea t : conversations) {
        JScrollPane scroll = new JScrollPane(conversations.get(0));
        scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        tabbedPane.add(scroll);
        //}
        tabbedPane.setTitleAt(0, "Welcome");

        splitPane = new JSplitPane(1, new JSplitPane(0, bSend, bSendFile), msgToSend);
        this.setLayout(new BorderLayout());

        //this.add(BorderLayout.NORTH, menu);
        this.add(BorderLayout.NORTH, infos);
        this.add(BorderLayout.EAST, tabbedPane);
        this.add(BorderLayout.WEST, scrollPanelist);
        this.add(BorderLayout.SOUTH, splitPane);


        bSendFile.addActionListener(this);
        bSend.addActionListener(this);
        bDisconnect.addActionListener(this);

        this.pack();
        this.setTitle("Chat System");
        this.setVisible(true);
        //setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        list.addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent arg0) {
                if (list.getSelectedValue() != null && list.getModel().getSize() != 0 && !arg0.getValueIsAdjusting()
                        && (parent.model.getHashmapConv().get((User) list.getSelectedValue())) == null) {
                    int choice = JOptionPane.showConfirmDialog(rootPane, "Do you want to start a chat with " + list.getSelectedValue().toString() + " ?");
                    if (choice == 0) {
                        parent.controller.performUserSelected((User) list.getSelectedValue());//parent.getCs().getModel().getHashmapUsers().get(val));
                    }
                }
            }
        });


        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent windowEvent) {
                System.out.println("Disconnection");
                parent.controller.performDisconnect();
            }
        });
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == bSend && list.getSelectedValue() != null) {
            User user = conversations.get(tabbedPane.getSelectedIndex()).getConversation().getRemoteUser();
            //System.out.println("You want to send this message: "
            //        + msgToSend.getText() + " to " + user.getHostname());
            parent.controller.performSendMessage(user.getUsername(),
                    msgToSend.getText());
            msgToSend.setText("");
        } else if (e.getSource() == bSendFile && list.getSelectedValue() != null) {
            User user = conversations.get(tabbedPane.getSelectedIndex()).getConversation().getRemoteUser();
            JFileChooser filechooser = new JFileChooser();
            int val = filechooser.showOpenDialog(rootPane);
            if (val == JFileChooser.APPROVE_OPTION) {
                System.out.println("You chose to send this file: "
                        + filechooser.getSelectedFile().getAbsolutePath() + " to " + tabbedPane.getTitleAt(tabbedPane.getSelectedIndex()));
                parent.controller.performSendFileRequest(user.getUsername(), filechooser.getSelectedFile().getName(),
                        filechooser.getSelectedFile().getAbsolutePath(), filechooser.getSelectedFile().length());
            }

        } else if (e.getSource() == bDisconnect) {
            System.out.println("Disconnection");
            parent.controller.performDisconnect();
        }
    }

    public void updateUsersList() {
        if (parent.model.getLocalUserIsConnected()) {
            list.setCellRenderer(new ListCellRenderer());
            this.pack();
        }
    }

    public void openConversation(Conversation c) {
        ConversationArea ca = new ConversationArea(c);
        conversations.add(ca);
        JScrollPane scroll = new JScrollPane(ca,
                JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        Component compo = tabbedPane.add(scroll);
        tabbedPane.setSelectedComponent(compo);
        tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), c.getRemoteUser().toString());
        list.setSelectedValue(c.getRemoteUser(), true);
    }

    public void updateConversationsList() {
        System.out.println("update conversationslist");
        if (parent.model.getLocalUserIsConnected()) {
            //System.out.println(parent.model.getConversations().toString());
            for (int i = 1; i < tabbedPane.getTabCount(); i++) {
                ConversationArea area = conversations.get(i);//new ConversationArea(conv);
                area.setText(area.getConversation().getHistory());
            }
        }

    }

    public boolean answerFileRequest(String username, String filename) {
        int choice = JOptionPane.showConfirmDialog(rootPane, "Do you want to accept this file: '"
                + filename + "' from " + username);
        if (choice == 0) {
            return true;
        } else {
            return false;
        }
    }

    public String answerFilepath() {
        JFileChooser filechooser = new JFileChooser();
        filechooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        filechooser.setDialogTitle("Choose a directory destination");
        filechooser.showOpenDialog(rootPane);
        return filechooser.getSelectedFile().getAbsolutePath();
    }
}
